<template>
  <view class="rf-index">
    <!--搜索导航栏-->
    <rf-search-bar
      @search="navToSearch"
      @tab="tabClick"
      :categoryList="categoryList"
      :merchantData="merchantData"
      :placeholder="hotSearchDefault"
    />

    <view class="main-content">
      <block v-if="currentCate === 0">
        <!-- 轮播图1 -->
        <view class="swiper">
          <view class="swiper-box">
            <rf-swipe-dot
              :info="slideshowList"
              mode="nav"
              :current="current"
              field="title"
            >
              <swiper @change="handleDotChange" autoplay="true">
                <swiper-item
                  v-for="(item, index) in slideshowList"
                  :key="index"
                >
                  <navigator
                    v-if="item.type === 'url'"
                    :url="'/pages/web-view/web-view?url=' + item.value"
                  >
                    <view class="swiper-item">
                      <image :src="item.image" mode="aspectFill" />
                    </view>
                  </navigator>
                  <view
                    class="swiper-item"
                    v-if="item.type === 'phone'"
                    @tap="handlePhone(item.value)"
                  >
                    <image :src="item.image" mode="aspectFill" />
                  </view>
                  <view
                    class="swiper-item"
                    v-if="item.type === 'product'"
                    @tap.stop="navTo(`/pages/product/product?id=${item.value}`)"
                  >
                    <image :src="item.image" mode="aspectFill" />
                  </view>
                  <view
                    class="swiper-item"
                    v-if="item.type === 'business'"
                    @tap.stop="navTo(`/pages/user/coupon/detail?id=${item.value}`)"
                  >
                    <image :src="item.image" mode="aspectFill" />
                  </view>
                  <view
                    class="swiper-item"
                    v-else
                  >
                    <image :src="item.image" mode="aspectFill" />
                  </view>
                </swiper-item>
              </swiper>
            </rf-swipe-dot>
          </view>
        </view>
        <!-- 分类列表 -->
        <swiper
          :indicator-active-color="themeColor.color"
          indicator-color="#666"
          :current="sweiperCurrent"
          :interval="interval"
          :duration="duration"
          :indicator-dots="true"
          :style="{ height: '400rpx' }"
          class="category-list-wrapper"
        >
          <swiper-item
            class="category-list"
            v-for="(item, index) in categoryList"
            :key="index"
          >
            <view
              v-for="(fItem, fIndex) in item"
              :key="fIndex"
              @tap="navToCategory(fItem)"
              class="category"
            >
              <view class="img">
                <image
                  :src="fItem.img_url || errorImage"
                  mode="aspectFill"
                ></image>
              </view>
              <view class="text in1line">{{ fItem.name }}</view>
            </view>
          </swiper-item>
        </swiper>
        <!--推荐商品-->
        <rf-floor-index v-if="bannerList.length>0"
          :banner="bannerList"
        />
      </block>
      <view class="index-cate-product-list">
        <rf-product-list
          :bottom="bottom"
          :list="categoryProductList"
        ></rf-product-list>
        <rf-load-more
          :status="loadingType"
          v-if="categoryProductList.length > 0"
        ></rf-load-more>
        <rf-empty
          :bottom="bottom"
          :info="'暂无该分类产品~'"
          v-if="categoryList.length === 0 && !productLoading"
        ></rf-empty>
      </view>
    </view>
    <!--页面加载动画-->
    <rfLoading isFullScreen :active="loading"></rfLoading>
    <rf-back-top :scrollTop="scrollTop"></rf-back-top>
    <rf-back-home></rf-back-home>
    <tab-bar :current="currentIndex" @change="tabchange"></tab-bar>
  </view>
</template>
<script>
import { productList } from "@/api/product";
import { home } from "@/api/home";
import rfSwipeDot from "@/components/rf-swipe-dot";
import rfFloorIndex from "@/components/rf-floor-index";
import rfSearchBar from "@/components/rf-search-bar";
import rfProductList from "@/components/rf-product-list";
import tabBar from "@/components/tabbar/index.vue";
export default {
  components: {
    rfFloorIndex,
    rfSwipeDot,
    rfProductList,
    rfSearchBar,
    tabBar,
  },
  data() {
    return {
      current: 0, // 轮播图index
      currentIndex: 0,
      sweiperCurrent: 0,
      autoplay: true,
      interval: 2000,
      duration: 500,
      categoryList: [],
      bannerList: [],
      swiperBoxNum: 1,
      slideshowList: [],
      loading: true,
      scrollTop: 0,
      kefuShow: true,
      loadingType: "more",
      hotSearchDefault: "请输入关键字",
      errorImage: this.$mAssetsPath.errorImage,
      categoryProductList: [], // 分类列表
      page: 1,
      currentCate: 0,
      productLoading: true,
      isOpenIndexCate: this.$mSettingConfig.isOpenIndexCate,
      moneySymbol: this.moneySymbol,
      merchantShow: false,
      merchantData: {},
    };
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },
  onLoad() {
    this.initData();
  },
  computed: {
    statusBar() {
      const e = uni.getSystemInfoSync();
      return e.statusBarHeight;
    },
    bottom() {
      let bottom = 0;
      /*  #ifdef H5  */
      bottom = 90;
      /*  #endif */
      return bottom;
    },
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.page = 1;
    this.getIndexList();
    this.getnewProductList("refresh");
  },
  // 上拉加载
  onReachBottom() {
    if (this.loadingType === "nomore") return;
    this.page++;
    this.getProductList(this.loadingType);
  },
  methods: {
    //拨打电话
    handlePhone(phone) {
      uni.makePhoneCall({
        // 手机号
        phoneNumber: phone,
        // 成功回调
        success: (res) => {
          console.log("调用成功!");
        },
        // 失败回调
        fail: (res) => {
          console.log("调用失败!");
        },
      });
    },
    tabchange(item) {
      this.$mRouter.push({ route: item.pagePath });
    },
    // 顶部tab点击
    tabClick({ id }) {
      this.currentCate = id;
      if (id === 0) return;
      this.loading = true;
      this.page = 1;
      this.productLoading = true;
      this.categoryProductList = [];
      this.getProductList(id);
    },
    // 获取产品列表
    async getProductList(type) {
      await this.$http
        .get(`${productList}`, {
          page: this.page,
        })
        .then(async (r) => {
          this.loading = false;
          this.productLoading = false;
          this.loadingType = r.data.data.length < 15 ? "nomore" : "more";
          this.categoryProductList = [
            ...this.categoryProductList,
            ...r.data.data,
          ];
        })
        .catch(() => {
          this.loading = false;
          this.productLoading = false;
        });
    },
    async getnewProductList(type) {
      await this.$http
        .get(`${productList}`, {
          page: this.page,
        })
        .then(async (r) => {
          if (type === "refresh") {
            uni.stopPullDownRefresh();
          }
          this.loading = false;
          this.categoryProductList = r.data.data;
        })
        .catch(() => {
          this.loading = false;
          this.productLoading = false;
        });
    },
    // 监听轮播图切换
    handleDotChange(e) {
      this.current = e.detail.current;
    },
    // 数据初始化
    initData() {
      // 首页数据
      this.getIndexList();
      this.getProductList();
    },
    // 通用跳转
    navTo(route) {
      
      this.$mRouter.push({ route });
    },
    // 跳转至分类模块
    navToCategory(item) {
      this.$mRouter.push({
        route: "/pages/index/engine",
        query: { id: item.id, name: item.name },
      });
    },
    // 通用跳转
    navToSearch() {
      this.$mRouter.push({
        route: `/pages/index/search/search?data=${JSON.stringify(this.search)}`,
      });
    },
    // 跳至广告图指定页面
    indexTopToDetailPage(item) {
      console.log(item);
      if (item.url) {
        // window.location.href =item.url
      }
    },
    // 获取主页数据
    async getIndexList(type) {
      await this.$http
        .get(`${home}`)
        .then(async (r) => {
          if (type === "refresh") {
            uni.stopPullDownRefresh();
          }
          // 首页参数赋值
          this.initIndexData(r.data);
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
          if (type === "refresh") {
            uni.stopPullDownRefresh();
          }
        });
    },
    // 首页参数赋值
    initIndexData(data) {
      this.bannerList = data.banner;
      this.slideshowList = data.slideshow;
      this.search = {};
      this.categoryList = data.category;
      this.categoryList = this.setTwoDimensionalArray(this.categoryList);
    },
    setTwoDimensionalArray(list) {
      const listResult = []; // 最终返回的二维数组
      for (let i = 0; i < Math.ceil(list.length / 8); i++) {
        listResult[i] = [];
        for (let j = 0; j < 8; j++) {
          // 如果是最后一个板块
          if (i === Math.ceil(list.length / 8) - 1) {
            if (Math.ceil(list.length % 8) !== 0) {
              // 只有最后一个板块的数据在余数以内的才赋值
              if (j < Math.ceil(list.length % 8)) {
                listResult[i][j] = list[i * 8 + j];
              }
            } else {
              // 如果刚好整整一个板块，则全部附上值
              listResult[i][j] = list[i * 8 + j];
            }
          } else {
            listResult[i][j] = list[i * 8 + j];
          }
        }
      }
      return listResult;
    },
    // 跳转至商品详情页
    navToDetailPage(data) {
      const { id } = data;
      if (!id) return;
      this.$mRouter.push({ route: `/pages/product/product?id=${id}` });
    },
    // 跳转至分类页
    toCategory() {
      this.$mRouter.switchTab({ route: "/pages/category/category" });
    },
  },
};
</script>
<style lang="scss">
page {
  // background-color: #fff;
}
.rf-index {
  background-color: $color-white;
  height: 100vh;
  .main-content {
    position: relative;
    z-index: 100;
    margin-top: -200upx;
    overflow: auto;
  }
  /*爆款拼团*/
  .wrapper {
    border-radius: 10upx;
    .h-list {
      background-color: $page-color-base;
      white-space: nowrap;
      padding: 0 $spacing-sm;
      .h-item {
        margin: $spacing-sm $spacing-sm $spacing-sm 0;
        display: inline-block;
        background-color: $color-white;
        font-size: $font-sm;
        width: 280upx;
        border-radius: 6upx;
        .h-item-img {
          display: inline-block;
          width: 280upx;
          height: 300upx;
          border-top-left-radius: 12upx;
          border-top-right-radius: 12upx;
          border-bottom: 1upx solid rgba(0, 0, 0, 0.01);
        }
        .title {
          width: 280upx;
          white-space: normal;
          height: 60upx;
          line-height: 30upx;
          font-size: $font-sm;
          padding: 0 $spacing-sm;
          margin: $spacing-sm 0;
        }
        .last-line {
          padding: 0 $spacing-sm $spacing-base;
          margin-bottom: 5upx;
          display: flex;
          justify-content: space-between;
          align-items: center; /* 垂直居中 */
          .red {
            font-size: $font-sm;
            margin-right: 4upx;
          }
        }
        .price {
          font-size: $font-base - 2upx;
          line-height: 1;
          .m-price {
            margin-left: 8upx;
            color: $font-color-light;
            font-size: $font-sm;
            text-decoration: line-through;
          }
        }
      }
    }
  }
  /*轮播图*/
  .swiper {
    width: 100%;
    margin-bottom: 20upx;
    display: flex;
    justify-content: center;
    .swiper-box {
      width: 92%;
      height: 40vw;
      overflow: hidden;
      border-radius: 15upx;
      box-shadow: 0upx 8upx 25upx rgba(0, 0, 0, 0.2);
      //兼容ios，微信小程序
      position: relative;
      z-index: 1;
      swiper {
        width: 100%;
        height: 40vw;
        swiper-item {
          image {
            width: 100%;
            height: 40vw;
          }
        }
      }
    }
  }
  /* 爆款推荐 */
  .hot-recommend {
    background-color: $color-white;
    display: flex;
    padding: $spacing-base $spacing-lg 0;
    .hot-recommend-image {
      width: 100%;
      height: 100%;
    }
    .left {
      flex: 3;
      height: 350upx;
      margin-right: 15upx;
    }
    .right {
      flex: 4;
      .hot-recommend-image {
        height: 170upx;
      }
    }
  }
  /*轮播图2*/
  .swiper-item-text {
    position: absolute;
    bottom: 16upx;
    left: 30upx;
    height: 48upx;
    line-height: 48upx;
    background: rgba(0, 0, 0, 0.2);
    width: 90%;
    color: $color-white;
    border-bottom-left-radius: 12upx;
    padding-left: 20upx;
  }
  /*新闻通知*/
  .swiper-slide-header {
    .iconfont {
      font-size: $font-lg + 8upx;
      font-weight: 600;
    }
  }
  /*分类列表*/
  .category-list-wrapper {
    .category-list {
      width: 100%;
      padding: $spacing-base;
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      .category {
        margin-top: 10upx;
        width: 25%;
        height: 132upx;
        display: flex;
        text-align: center;
        flex-wrap: wrap;
        .img {
          width: 100%;
          display: flex;
          justify-content: center;
          image {
            width: 12vw;
            height: 12vw;
            border-radius: 50%;
          }
        }
        .text {
          margin-top: 16upx;
          width: 100%;
          display: flex;
          justify-content: center;
          font-size: 24upx;
          color: #3c3c3c;
        }
      }
    }
  }
  /*版权显示*/
  .copyright {
    margin: 10upx 0;
    width: 100%;
    text-align: center;
    color: #666;

    a {
      display: block;
      color: #666;
      text-decoration: none;
    }
  }
  /*限时抢购*/
  .order-item {
    display: flex;
    flex-direction: column;
    background: #fff;
    padding: 0 30upx;
    margin-bottom: 20upx;

    .goods-box-single {
      display: flex;
      padding: 40upx 10upx 10upx;
      height: 330upx;
      border-radius: 12upx;
      margin-top: 20upx;
      box-shadow: 2px 2px 10px rgba(66, 135, 193, 0.2); // 阴影
      border-bottom: 1px solid rgba(0, 0, 0, 0.05); // 边框
      position: relative;

      .goods-img {
        display: block;
        border-radius: 12upx;
        width: 190upx;
        height: 200upx;
      }

      .right {
        flex: 1;
        display: flex;
        flex-direction: column;
        padding: 0 30upx 0 24upx;
        overflow: hidden;

        .title {
          font-weight: bold;
          line-height: 1.2;
          margin: 10upx 0;
        }

        .attr-box {
          line-height: 1.2;
          margin-bottom: 8upx;
          margin-left: 10upx;
        }

        .last-line {
          margin-top: 3upx;
          display: flex;
          justify-content: space-between;
          align-items: center; /* 垂直居中 */
          .red {
            margin-right: 4upx;
          }
        }

        .price {
          font-size: $font-lg;
          line-height: 1;
          .m-price {
            margin-left: 8upx;
            color: $font-color-light;
            font-size: $font-sm;
            text-decoration: line-through;
          }
        }

        .triangle-wrapper {
          position: absolute;
          overflow: hidden;
          top: 0;
          right: 0;
          border-radius: 12upx;

          .triangle {
            color: #5eba8f;
            width: 0;
            height: 0;
            border-top: 120upx solid;
            opacity: 0.8;
            border-left: 120upx solid transparent;
          }

          .triangle-content {
            position: absolute;
            top: 28upx;
            right: 0;
            transform: rotate(45deg);
            font-size: $font-sm - 2upx;
            color: #fff;
          }
        }
      }
    }

    .action-box {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      height: 90upx;
      position: relative;

      .discount-time {
        font-size: $font-sm;
        color: $uni-color-success;
        margin-right: 20upx;
      }
    }
  }
  .index-cate-product-list {
    padding-top: $spacing-sm;
    background-color: $page-color-base;
    .no-data {
      margin: 48upx 0;
      color: $font-color-light;
      display: flex;
      justify-content: center;
      align-items: center;
      .iconfont {
        margin-right: 20upx;
        font-size: $font-lg + 16upx;
      }
    }
  }
}
</style>
